<?php 
namespace app\admin\controller;

use app\common\model\admin\AdminParam;
use think\Exception;
use think\Db;
use app\common\controller\Log;
use app\common\model\user\Users;

class Param extends Base
{
	/**
	 * 获取系统参数
	 * @return unknown
	 */
	public function paramList()
	{
		$user_id = $this -> request->param('user_id');
		if(!$user_id)$info = AdminParam::get(1);
		else $info = AdminParam::where(['user_id' => $user_id])->find();
		return jsonSuccess($info);
	}
	
	/**
	 * 修改参数
	 * @throws Exception
	 * @return unknown
	 */
	public function updateParam()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			foreach ($data as $k => $v) {
				if($v == '')unset($data[$k]);
			}
			if(strtotime($data['trade_start']) > strtotime($data['trade_end']))
				throw new Exception('挂卖时间错误');
			$info = AdminParam::get($data['id']);
			//修改
			$data['update_time'] = time();
			unset($data['create_time']);
			$info->save($data);
			//添加日志
			Log::addLog(2, "修改参数");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 添加参数
	 * @throws Exception
	 * @return unknown
	 */
	public function addParam()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			if(!$user_id)throw new Exception('会员账号不存在');
			if(AdminParam::where(['user_id' => $user_id , 'state' => 1])->value('id'))
				throw new Exception('会员已设置的参数');
			$data['user_id'] = $user_id;
			$user_name = $data['user_name'];
			unset($data['user_name']);
			$data['create_time'] = time();
			$data['update_time'] = time();
			AdminParam::create($data);
			//添加日志
			Log::addLog(1, "给会员【{$user_name}】设置参数");
			Db::commit();
		}catch (Exception $e){
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}
	
	/**
	 * 获取会员参数列表
	 * @return unknown
	 */
	public function userParam()
	{
		$user_name = $this->request->post('user_name');
		//初始化查询条件
		$where = ['state' => 1 ,'user_id' => ['neq',0]];
		if(!empty($user_name)){
			$user_id = Users::where(['user_name' => $user_name])->value('id');
			$where['user_id'] = $user_id;
		}
		$list = AdminParam::where($where)->paginate()->toArray();
		foreach ($list['data'] as &$rows ) {
			$rows['user_name'] = Users::where(['id' => $rows['user_id']])->value('user_name');
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 删除用户参数
	 * @return unknown
	 */
	public function deleteParam()
	{
		$id = $this->request->post('id');
		try {
			$param = AdminParam::get($id);
			$param->save(['state' => 0,'update_time' => time(0)]);
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}
}